import sys
import os
import datetime

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from database import Database

class DormitoryAllocator:
    def __init__(self):
        self.db = Database()
    
    def allocate_dormitory(self, student_id, dormitory_id):
        """
        为学生分配宿舍
        
        参数:
            student_id (str): 学生学号
            dormitory_id (int): 宿舍ID
        
        返回:
            bool: 分配成功返回True，否则返回False
        """
        try:
            # 验证输入
            if not student_id or not dormitory_id:
                print("错误：学生学号和宿舍ID都必须提供")
                return False
            
            # 连接数据库
            self.db.connect()
            
            # 检查学生是否存在
            self.db.cursor.execute(
                "SELECT id, name, gender, dormitory_id FROM student WHERE student_id = ?",
                (student_id,)
            )
            student = self.db.cursor.fetchone()
            if not student:
                print(f"错误：学号为 {student_id} 的学生不存在")
                self.db.close()
                return False
            
            student_db_id, student_name, student_gender, current_dormitory_id = student
            
            # 检查学生是否已分配宿舍
            if current_dormitory_id:
                print(f"错误：学生 {student_name} 已分配宿舍，请先退宿或调整宿舍")
                self.db.close()
                return False
            
            # 检查宿舍是否存在
            self.db.cursor.execute(
                "SELECT id, building, room_number, capacity, current_count, status FROM dormitory WHERE id = ?",
                (dormitory_id,)
            )
            dormitory = self.db.cursor.fetchone()
            if not dormitory:
                print(f"错误：ID为 {dormitory_id} 的宿舍不存在")
                self.db.close()
                return False
            
            dorm_id, building, room_number, capacity, current_count, status = dormitory
            
            # 检查宿舍状态
            if status != 'available':
                print(f"错误：宿舍 {building}-{room_number} 当前状态为 {status}，不可分配")
                self.db.close()
                return False
            
            # 检查宿舍是否已满
            if current_count >= capacity:
                print(f"错误：宿舍 {building}-{room_number} 已满员 ({current_count}/{capacity})")
                self.db.close()
                return False
            
            # 检查宿舍性别匹配
            if current_count > 0:
                # 获取宿舍内学生的性别
                self.db.cursor.execute(
                    """SELECT s.gender FROM student s 
                    WHERE s.dormitory_id = ? LIMIT 1""",
                    (dorm_id,)
                )
                dorm_gender = self.db.cursor.fetchone()
                if dorm_gender and dorm_gender[0] != student_gender:
                    print(f"错误：宿舍 {building}-{room_number} 已有不同性别的学生")
                    self.db.close()
                    return False
            
            # 更新学生的宿舍ID
            self.db.cursor.execute(
                "UPDATE student SET dormitory_id = ? WHERE id = ?",
                (dorm_id, student_db_id)
            )
            
            # 更新宿舍当前人数
            self.db.cursor.execute(
                "UPDATE dormitory SET current_count = current_count + 1 WHERE id = ?",
                (dorm_id,)
            )
            
            # 添加分配记录
            allocation_date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            self.db.cursor.execute(
                "INSERT INTO allocation (student_id, dormitory_id, allocation_date, status) VALUES (?, ?, ?, ?)",
                (student_db_id, dorm_id, allocation_date, 'active')
            )
            
            self.db.conn.commit()
            print(f"成功：学生 {student_name} 已分配到宿舍 {building}-{room_number}")
            return True
        except Exception as e:
            print(f"错误：分配宿舍时发生错误 - {str(e)}")
            return False
        finally:
            self.db.close()
    
    def batch_allocate_dormitory(self, allocations):
        """
        批量分配宿舍
        
        参数:
            allocations (list): 分配信息列表，每个元素是包含学生学号和宿舍ID的元组 (student_id, dormitory_id)
        
        返回:
            tuple: (成功分配数量, 总数量)
        """
        success_count = 0
        total_count = len(allocations)
        
        for allocation in allocations:
            student_id, dormitory_id = allocation
            if self.allocate_dormitory(student_id, dormitory_id):
                success_count += 1
        
        return success_count, total_count

# 如果直接运行此文件，提供命令行界面
if __name__ == "__main__":
    allocator = DormitoryAllocator()
    
    print("===== 宿舍分配 =====")
    print("1. 分配单个学生宿舍")
    print("2. 批量分配宿舍")
    
    choice = input("请选择操作 (1-2): ")
    
    if choice == '1':
        student_id = input("请输入学生学号: ")
        dormitory_id = input("请输入宿舍ID: ")
        
        try:
            dormitory_id = int(dormitory_id)
            allocator.allocate_dormitory(student_id, dormitory_id)
        except ValueError:
            print("错误：宿舍ID必须是数字")
    
    elif choice == '2':
        print("\n批量分配宿舍 (每行输入一个分配信息，格式：学号,宿舍ID)")
        print("输入空行结束输入\n")
        
        allocations = []
        while True:
            line = input("> ")
            if not line:
                break
            
            parts = [part.strip() for part in line.split(',')]
            if len(parts) != 2:
                print("错误：输入格式不正确，请确保包含学号和宿舍ID")
                continue
            
            student_id = parts[0]
            try:
                dormitory_id = int(parts[1])
                allocations.append((student_id, dormitory_id))
            except ValueError:
                print(f"错误：宿舍ID '{parts[1]}' 必须是数字，此条记录将被跳过")
        
        if allocations:
            success_count, total_count = allocator.batch_allocate_dormitory(allocations)
            print(f"\n批量分配完成：成功 {success_count}/{total_count}")
        else:
            print("没有输入任何分配信息")
    
    else:
        print("无效的选择")